package com.xszx.knowledge.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xszx.knowledge.dto.UserDTO;
import com.xszx.knowledge.entity.User;
import com.xszx.knowledge.exception.DevException;
import com.xszx.knowledge.exception.DevExceptionCode;
import com.xszx.knowledge.mapper.UserMapper;
import com.xszx.knowledge.service.UserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xszx.knowledge.util.Result;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.util.ObjectUtils;

import java.util.List;

/**
 * <p>
 * 用户 服务实现类
 * </p>
 *
 * @author wencai
 * @since 2023/04/25 21:00
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    public static Logger LOG = LoggerFactory.getLogger(UserServiceImpl.class);
    //根据用户名查询数据
    @Override
    public User getUserByLoginName(String loginName){
        List<User> userList = list(new QueryWrapper(new User(loginName)));
        if(userList != null && userList.size()>0){
            return userList.get(0);
        }else{
            return null;
        }
    }
    //保存用戶信息并且进行相关验证
    public Result saveUser(User user) {
        if(!ObjectUtils.isEmpty(user) && user.getId() == null){
            //执行添加操作前要判断用户名在数据库中是否存在
            User u = getUserByLoginName(user.getLoginName());
            if(u == null){
                return  Result.ifSuccess(save(user));
            }else{
                //return Result.error().message("用戶名已存在");
                throw new DevException(DevExceptionCode.USER_LOGIN_NAME_EXIST);//抛出自定义异常
            }
        }else{
            return Result.ifSuccess(updateById(user));
        }
    }

    @Override
    public User login(UserDTO userDTO) {
        //后台进行二次加密
        userDTO.setPassword(DigestUtils.md5DigestAsHex(userDTO.getPassword().getBytes()));
        //根据用户名查找用户
        User user = getUserByLoginName(userDTO.getLoginName());
        //判断师傅能够登录
        if(!ObjectUtils.isEmpty(user)){//用户名存在的
            //比较二次加密的密码
            if(user.getPassword().equals(userDTO.getPassword())){
                return user;
            }else{//密码不正确
                LOG.info("密码为{}错误", userDTO.getLoginName());
                //消息通知
               throw  new DevException(DevExceptionCode.LOGIN_USER_ERROR);
            }
        }else{//用户就不存在
              LOG.info("用户名{}不存在", userDTO.getLoginName());
              //消息通知
              throw  new DevException(DevExceptionCode.LOGIN_USER_ERROR);
        }
    }
}
